package com.example.app.base

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.view.ViewGroup.MarginLayoutParams
import android.view.WindowManager
import androidx.core.view.updateLayoutParams
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PermissionUtils
import com.example.app.dialog.CommonConfirmDialog
import com.example.app.dialog.CommonLoadingDialog
import com.example.app.manager.BirthdayPickerManager
import com.example.app.manager.giftplay.SvgaManager
import com.example.app.moudle.main.MainActivity
import com.libcommon.PermissionManager
import com.luck.picture.lib.manager.photo.PhotosSelectManager
import com.lxj.xpopup.core.BasePopupView
import com.weikaiyun.fragmentation.SupportFragment

/**
 * Created on 2022/12/23.
 * @author Joker
 * Des:
 */

abstract class BaseFragment : SupportFragment() {

    abstract fun getLogTag(): String

    private var loadingDialog: BasePopupView? = null
    private var settingDialog: BasePopupView? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        LogUtils.i("${getLogTag()},onViewCreated")
        if (isNeedObserveKeyboardChange()) {
            //注册键盘弹出
            initKeyboard()
        }
    }

    override fun onNewBundle(args: Bundle?) {
        super.onNewBundle(args)
        LogUtils.d("${getLogTag()},onNewBundle args=${args}")
    }

    override fun onResume() {
        super.onResume()
        LogUtils.i("${getLogTag()},onResume")
        activity?.window?.setSoftInputMode(if (isKeyboardCoverMode()) WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING else WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
    }

    override fun onVisible() {
        super.onVisible()
        LogUtils.d("${getLogTag()},onVisible")
    }

    override fun onInvisible() {
        super.onInvisible()
        LogUtils.d("${getLogTag()},onInvisible")
    }

    override fun onPause() {
        super.onPause()
        LogUtils.i("${getLogTag()},onPause")
    }

    override fun onStop() {
        super.onStop()
        LogUtils.i("${getLogTag()},onStop")
    }

    override fun onDestroy() {
        getMainActivity()?.let {
            KeyboardUtils.hideSoftInput(it)
            KeyboardUtils.unregisterSoftInputChangedListener(it.window)
        }
        PhotosSelectManager.onRelease()
        SvgaManager.clearCache()
        dismissLoadingDialog()
        BirthdayPickerManager.dismissBirthdayPicker()
        dismissSettingDialog()
        super.onDestroy()
        LogUtils.i("${getLogTag()},onDestroy")
    }

    override fun onBackPressedSupport(): Boolean {
        LogUtils.d("${getLogTag()},onBackPressedSupport")
        return super.onBackPressedSupport()
    }

    /**
     * 监听键盘显示与否
     */
    private fun initKeyboard() {
        getMainActivity()?.let {
            KeyboardUtils.fixAndroidBug5497(it)
            KeyboardUtils.registerSoftInputChangedListener(it) { height ->
                LogUtils.dTag(getLogTag(), "键盘高度=$height")
                //通知键盘显示和关闭了
                onKeyboardHighChange(height)
            }
        }
    }

    /**
     * 页面内异步操作都建议加上这个判断
     */
    fun isFragmentDestroyed() = !(isAdded && !isDetached && context != null)

    /** 显示加载框 */
    fun showLoadingDialog(isCancelTouchOutSide: Boolean = true) {
        if (loadingDialog?.isShow == true) return

        loadingDialog = CommonLoadingDialog.show(context, isCancelTouchOutSide)
    }

    /** 关闭加载框 */
    fun dismissLoadingDialog() {
        loadingDialog?.dismiss()
        loadingDialog = null
    }

    fun getMainActivity() = activity as? MainActivity?

    fun getTopF() = topFragment as BaseFragment

    /**
     * 适配沉浸式状态栏
     */
    fun adaptStatusBar(view: View, extraMargin: Float = 10f) {
        view.updateLayoutParams<MarginLayoutParams> {
            topMargin = (getMainActivity()?.statusBarHigh ?: 0) + ConvertUtils.dp2px(extraMargin)
        }
    }

    fun getStatusBarH(): Int = getMainActivity()?.statusBarHigh ?: 0

    /**
     * 键盘覆盖模式
     */
    open fun isKeyboardCoverMode(): Boolean = true

    open fun isNeedObserveKeyboardChange(): Boolean = false

    open fun onKeyboardHighChange(height: Int) {}

    /**
     * 检查app所需必要权限
     */
    @SuppressLint("WrongConstant")
    fun checkAppPermission(permissionGroup: Array<String>, mOnGranted: ((permissions: MutableList<String>?) -> Unit)? = null) {
        // 版本大于6.0动态申请权限
        PermissionManager.checkPermission(activity, permissionGroup, mOnGranted, mOnDenied = { _, _, _ -> showSettingDialog() })
    }

    /**
     * 提示给予权限
     */
    fun showSettingDialog() {
        dismissSettingDialog()
        settingDialog = CommonConfirmDialog.show(
            title = "To access your permission, go to System Settings",
            onConfirm = { PermissionUtils.launchAppDetailsSettings() })
    }

    private fun dismissSettingDialog() {
        settingDialog?.dismiss()
        settingDialog = null
    }
}